package edu.suda.config;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.InputStream;

/*****************************
 * @Description: mybatis框架的配置类
 * @Author: 苏大
 */
public class MybatisConfig {
    private static final String CONFIG_PATH = "mybatis-config.xml";

    private static SqlSessionFactory sqlSessionFactory;

    //初始化sqlSessionFactory
    static {
       try(InputStream in = Resources.getResourceAsStream(CONFIG_PATH);) {
           sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
       } catch (Exception e) {
           e.printStackTrace();
       }
    }

    /**********
     * 对外提供一个获取SqlSession的方法
     */
    public static SqlSession getSqlSession(boolean autoCommit) {
        return sqlSessionFactory == null ? null : sqlSessionFactory.openSession(autoCommit);
    }
}
